<template>
  <!--问题反馈单-->
  <div  v-loading.fullscreen.lock="fullscreenLoading"></div>
  <basic-dialog v-model="dialog.showDialog" :title="dialog.title" width="1800"
                :autoClose="false" :hideFooter="true">
    <basic-crud  ref="crudRef" :option="options" :autoLoad="false"
                 v-model="formData"
                 :fastSearch="{}"
                 :before-open="beforeOpen"
                 @row-click="handleRowClick"
                 :row-save="handleAdd"
                 :row-update="handleEdit">
      <template #fileNames="{ row }">
        <el-button type="text" v-for="file in row.fileList" :key="file.id"  @click="downloadFileHandler(file)">{{
            `${file.showName}.${file.fileExtension};`
          }}</el-button>
      </template>
      <template #fileNames-form>
        <el-button type="text" v-for="file in formData.fileList" :key="file.id"  @click="downloadFileHandler(file)">{{
            `${file.showName}.${file.fileExtension};`
          }}</el-button>
      </template>
      <template #menu-right>
        <div style="display: flex;align-items: center;margin-right: 10px;">
          <span style="width: 10px;text-align: right"></span>
          <el-input v-model="fastSearchText" clearable :placeholder="'请输入编号回车查询'" size="small"
                    style="margin-right: 5px;width: 400px" @clear="fastSearchHandler"
                    @keyup.enter.native="fastSearchHandler">
            <template #suffix>
              <el-icon class="el-input__icon" style="cursor: pointer" @click="fastSearchHandler"><search /></el-icon>
            </template>
          </el-input>
        </div>
      </template>
      <template #menu-left>
        <avue-upload v-if="!onlyShow"  :showFileList="false" style="margin-left: 10px;"
            :data="extraData"
            :fileText="'文件上传'"
            :action="uploadObject.action"
            :headers="uploadObject.headers"
            :propsHttp="uploadObject.propsHttp"
            :upload-after="uploadAfter"
            :upload-before="uploadBefore"
            type="upload"
        ></avue-upload>
      </template>
      <template #menu="{ row, index }">
        <el-button v-if="row.status === 'Created'"
                   type="text"
                   icon="edit"
                   @click="crudRef.crudRef.rowEdit(row, index)"
        >编辑
        </el-button>
        <el-button v-if="!onlyShow"
                   type="danger"
                   link
                   icon="delete"
                   @click="handleDelete(row)"
        >删除
        </el-button>
      </template>
    </basic-crud>
    <BasicCrudUserRefer ref="crudReferRef" v-model="UserVisible" selectType="radio"
                        @submit="handleSetUserSubmit"></BasicCrudUserRefer>
  </basic-dialog>
</template>

<script setup>
import {defineExpose, nextTick, ref} from "vue";
import {ElMessage} from "element-plus";
import { formatDate,formatMilliseconds } from "@/utils/formatTime";
import {downloadFile} from "@/utils/file.js";
import { getWorkOrder } from "@/apis/mes/processTask";
import {useUserStore} from '@/store/user';
import {
  apiGetList,
  postAdd,
  putEdit,
  deleteDel,
} from "@/apis/mes/problemFeedback.js";
const {token,userInfo} = useUserStore();

const emits = defineEmits(['refresh-parent'])

const dialog = ref({
  showDialog: false,
  title: "问题反馈单"
})

const uploadObject = ref({
  propsHttp: {
    res: "obj",
    name: "obj.name",
    url: "fileViewUrl",
  },
  headers: {
    'h-authorization-token': token
  },
  action: '/API/mes/fileController/uploadFile',
});

const parentRow = ref({});
const onlyShow = ref(false);
const usedSpecFlag = ref(false);
const doFirst = ref(false);
const searchData=ref({})

// 打开新增编辑对话框
const openDialog = (row, onlyShowValue,usedSpecFlagValue) => {
  usedSpecFlag.value=usedSpecFlagValue || false;//是否从规程添加
  doFirst.value = false;
  parentRow.value=row;
  onlyShow.value=onlyShowValue
  options.value.addBtn= !onlyShow.value
  options.value.menu= !onlyShow.value
  dialog.value.showDialog = true;
  getTableList()
};
const crudRef=ref(null);
const formData=ref({})
const options= ref({
  addBtn: !onlyShow.value,
  editBtn: false,
  delBtn: false,
  refreshBtn: false,
  align: "center",
  height: "570px",
  menu: !onlyShow.value,
  menuWidth: 180,
  column: [{
    label: "状态",
    prop: "status",
    width: 80,
    slot: true,
    display: false,
    statusTag: true,
    statusTypeMap: {
      Auditing: 'warning',
      Released: 'success',
    }
  },{
      label: "编号",
      prop: "code",
      overHidden: true,
      minWidth: 180,
      display: false,
    },
    {
      label: "反馈人",
      prop: "proposerName",
      overHidden: true,
      minWidth: 110,
      display: false,
      formatter:(row)=>{
        return row.proposer + " " + row.proposerName;
      }
    },
    {
      label: "创建时间",
      prop: "proposeTime",
      overHidden: true,
      minWidth: 130,
      type:'datetime',
      format:'yyyy-MM-dd HH:mm',
      display: false,
      formatter: (row) => {
        return formatDate(row.proposeTime, "yyyy-MM-dd HH:mm");
      },
    },
    {
      label: "结束时间",
      prop: "zeroingTime",
      overHidden: true,
      minWidth: 130,
      type:'datetime',
      format:'yyyy-MM-dd HH:mm',
      display: false,
      formatter: (row) => {
        return formatDate(row.zeroingTime, "yyyy-MM-dd HH:mm");
      },
    },
    {
      label: '问题类型',
      prop: 'problemClassifysText',
      width: 180,
      display: false,
      overHidden: true,
      span: 24,
    },
    {
      label: "问题描述",
      prop: "problemDesc",
      overHidden: true,
      minWidth: 150,
      display: false,
    },
    {
      label: "解决方案",
      prop: "solution",
      overHidden: true,
      minWidth: 200,
      display: false,
    },{
      label:'责任人',
      prop:'dutyUserName',
      display:false,
      width:80
    },{
      label:'责任部门',
      prop:'dutyDeptName',
      display:false,
      width:90
    },{
      label: "附件",
      prop: "fileNames",
      minWidth: 500,
      editDisplay:false,
      addDisplay:false,
      formslot:true,
      viewDisplay:false,
      span:24
    }],
  group:[
    {
      label: "",
      prop: "xcinfo",
      labelWidth:100,
      column: [
        {
          label: "编号",
          prop: "code",
          gutter: 32,
          disabled: true,
          placeholder: "后台自动生成",
          span: 12,
        },
        {
          label: "单据状态",
          prop: "status",
          gutter: 32,
          type: "select",
          dicData: [
            {
              label: "未处理",
              value: "Created",
            },
            {
              label: "已处理",
              value: "Released",
            },
          ],
          value: "Created",
          span: 12,
        },
        {
          label: "型号",
          prop: "modelName",
          gutter: 32,
          disabled: true,
          span: 12,
        },
        {
          label: "产品名称",
          prop: "productName",
          disabled: true,
          gutter: 32,
          span: 12,
        },
        {
          label: "产品编号",
          prop: "productCode",
          gutter: 32,
          disabled: true,
          span: 12,
        },
        {
          label: "工序号",
          prop: "processCode",
          gutter: 32,
          disabled: true,
          span: 12,
        },
        {
          label: "工序名称",
          prop: "processName",
          gutter: 32,
          disabled: true,
          span: 12,
        },
        {
          label: "反馈人",
          prop: "proposerName",
          gutter: 32,
          disabled: true,
          span: 12,
        },

        {
          label: "创建时间",
          prop: "proposeTime",
          type: "datetime",
          value: formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"),
          gutter: 32,
          formatter: (row) => {
            return formatDate(row.proposeTime, "yyyy-MM-dd HH:mm:ss");
          },
        },
        {
          label: "结束时间",
          prop: "zeroingTime",
          type: "datetime",
          gutter: 32,
          formatter: (row) => {
            return formatDate(row.zeroingTime, "yyyy-MM-dd HH:mm:ss");
          },
        },
        {
          label:'问题类型',
          prop:'problemClassifys',
          type:'checkbox',
          border: true,
          dicData: [{
            label:'人力问题',
            value:'manpowerConflict'
          },{
            label:'设备资源冲突',
            value:'deviceConflict'
          },{
            label:'设备故障',
            value:'deviceBreakdown'
          },{
            label:'物料未齐备',
            value:'supportUnComplete'
          },{
            label:'物料故障',
            value:'materialProblem'
          },{
            label:'设计文件问题',
            value:'designFileProblem'
          },{
            label:'工艺文件问题',
            value:'processFileProblem'
          },{
            label:'软件问题',
            value:'softwareProblem'
          },{
            label:'生产环境问题',
            value:'envProblem'
          },{
            label:'环境试验资源冲突',
            value:'envTestClash'
          },{
            label:'其他问题',
            value:'otherProblem'
          }],
          span:24
        },
        {
          label:'责任人',
          prop:'dutyUserName',
          span: 12,
        }, {
          label: '责任部门',
          prop: 'dutyDeptName',
          span: 12,
        },
        {
          label: "问题描述",
          prop: "problemDesc",
          type: "textarea",
          gutter: 32,
          minRows: 3,
          maxRows: 5,
          span: 24,
        },
        {
          label: "解决方案",
          prop: "solution",
          type: "textarea",
          gutter: 32,
          minRows: 3,
          maxRows: 5,
          span: 24,
        },
        {
          label: "附件",
          prop: "fileNames",
          minWidth: 300,
          editDisplay:false,
          addDisplay:false,
          formslot:true,
          viewDisplay:true,
          span:24
        }
      ],
    },
  ]
})
const problemClassifysList={
  "manpowerConflict": "人力问题",
  "deviceConflict": "设备资源冲突",
  "deviceBreakdown": "设备故障",
  "supportUnComplete": "物料未齐备",
  "materialProblem":'物料故障',
  'designFileProblem':'设计文件问题',
  'processFileProblem':'工艺文件问题',
  'softwareProblem':'软件问题',
  'envProblem':'生产环境问题',
  'envTestClash':'环境试验资源冲突',
  'otherProblem':'其他问题',
}

const fullscreenLoading = ref(false)
const getTableList=()=> {
  fullscreenLoading.value = true
  if(usedSpecFlag.value){
    searchData.value={
      specificationTaskId:parentRow.value.id,
      usedSpecFlag:usedSpecFlag.value
    }
  }else {
    searchData.value={
      processTaskId:parentRow.value.id
    }
  }
  apiGetList(searchData.value,fullscreenLoading).then((res) => {
    if (res.success) {
      if (!onlyShow.value && res.total == 0 && !doFirst.value) {
        crudRef.value.crudRef.rowAdd();
      }else {
        if( res.data?.length>0){
          const data=res.data.map(record=>{
            let text= [];
            record.problemClassifys?.map(val=>{
              text.push(problemClassifysList[val]);
            });
            record['problemClassifysText'] =  text.join('/');
            return record
          })
          crudRef.value.tableData = data;
        }
        doFirst.value = true;
        crudRef.value.pageData.total = res.total;
      }
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(() => {ElMessage.error("获取列表数据失败!")});
}

const fastSearchText=ref('')
//多属性快速查询
const fastSearchHandler=()=> {
  if(fastSearchText.value){
    searchData.value={
      processTaskId: parentRow.value.id,
      fastColumn:'code',
      fastText:fastSearchText.value
    }
  }else{
    searchData.value={
      processTaskId: parentRow.value.id
    }
  }
  getTableList();
}

const currentRow=ref(null);
const extraData=ref({})
const handleRowClick=(row) =>{
  currentRow.value=row
  extraData.value={
    ownId:row.id,
    ownBus:row.bus
  }
}

const uploadBefore=(file, done, loading)=> {
  if (!extraData.value.ownId) {
    ElMessage.error("请先点击行数据选中一条问题反馈单信息！");
    loading();
  } else {
    done();
  }
}
//上传后事件
const uploadAfter=(res, done, loading)=> {
  ElMessage.success("上传成功！");
  getTableList();
  loading();
  done();
  extraData.value={}
}

const beforeOpen=(done, type)=> {
  if (type == "add") {
    if (usedSpecFlag.value) {
      //规程
      formData.value.modelName = parentRow.value.modelName;
      formData.value.productId = parentRow.value.pdmProduct;
      formData.value.productName = parentRow.value.pdmProductName;
      formData.value.productCode = parentRow.value.pdmProductCode;
      formData.value.proposerName = userInfo.name;
      formData.value.proposerId = userInfo.id;
      formData.value.proposer = userInfo.code;
      formData.value.usedSpecFlag = usedSpecFlag.value;
      formData.value.specificationTaskId = parentRow.value.id;
      done();
    } else {
      //先从后台获取下工单的信息，用于显示产品等几个属性
      getWorkOrder(parentRow.value.id).then((obj) => {
        if (
            !obj.pdmProductCode ||
            obj.pdmProductCode == null ||
            obj.pdmProductCode == ""
        ) {
          return ElMessage.error("任务的产品编号都还没有添加，请先执行开工");
        }
        formData.value.modelName = obj.modelName;
        formData.value.productId = obj.pdmProduct;
        formData.value.productName = obj.pdmProductName;
        formData.value.productCode = obj.pdmProductCode;
        formData.value.processCode = parentRow.value.code;
        formData.value.processName = parentRow.value.name;
        formData.value.proposerName = userInfo.name;
        formData.value.proposerId = userInfo.id;
        formData.value.proposer = userInfo.code;
        formData.value.processTaskId = parentRow.value.id;
        done();
      });
    }
  } else if (type == 'edit') {
    if (formData.value.status === "Released") {
      return ElMessage.error("已经处理完成的单据，不能再修改了");
    } else {
      done();
    }
  } else {
    done();
  }
}
// 新增
const handleAdd=(form, done, loading)=> {
  form.proposeTime = formatMilliseconds(new Date(form.proposeTime));
  if (typeof form.zeroingTime === "object" && form.zeroingTime instanceof Date) {
    form["zeroingTime"] = formatMilliseconds(form.zeroingTime);
  }
  if (form.problemClassifys) {
    form.problemClassify = formData.value.problemClassifys.join(",");
  }
  postAdd(form).then((res) => {
    ElMessage.success("新增数据成功!");
    refreshHandler();
  }).finally((res) => {
    loading()
    done(form);
  });
}
// 编辑
const handleEdit=(form, index, done, loading)=> {
  form.proposeTime = formatMilliseconds(new Date(form.proposeTime));
  if (typeof form.zeroingTime === "object" && form.zeroingTime instanceof Date) {
    form["zeroingTime"] = formatMilliseconds(form.zeroingTime);
  } else if (typeof form.zeroingTime === "string") {
    form["zeroingTime"] = formatMilliseconds(new Date(form.zeroingTime));
  }
  if (form.problemClassifys) {
    form.problemClassify = formData.value.problemClassifys.join(",");
  }
  putEdit(form).then((res) => {
        ElMessage.success("修改数据成功!");
        getTableList();
        done(form);
      }).finally((res) => {
    loading()
    done(form);
  });
}

// 删除
const handleDelete=(row)=> {
  if (row.status != "Created") {
    return ElMessage.success("当前状态不允许删除");
  }
  ElMessageBox.confirm(`此操作将永久删除数据, 是否继续?`, "提示").then(() => {
    deleteDel(row.id).then((res) => {
      ElMessage.success("删除成功");
      doFirst.value = true;
      refreshHandler();
    });
  }).catch(() => {
      });
}

const UserVisible = ref(false);
const crudReferRef=ref(null)
// 用户参照回填
const handleSetUserSubmit = (selections) => {
  if(selections?.length>0) {
    formData.value.dutyUserId = selections[0].id;
    formData.value.dutyUserName = selections[0].name;
  }
  crudReferRef.value.handlerCancel();
};
const refreshHandler=()=> {
  getTableList();
  emits('refresh-parent')
}
//文件下载
const downloadFileHandler=async (row)=> {
  downloadFile(row.id, row.name, "/mes");
}
defineExpose({
  openDialog
})
</script>

<style lang="scss" scoped>
::v-deep {
  .el-checkbox.is-bordered {
    width: 145px;
    margin-right: 20px
  }
}
</style>